<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
	<th:block th:include="include :: header('新增训练任务')" />
	<!-- 引入 SweetAlert2 CSS -->
<!--	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">-->
<!--	<link rel="stylesheet" href="/sweetalert2-11.12.2/cypress/styles.css"/>-->
	<!-- 引入 SweetAlert2 JS -->
<!--	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>-->
	<script src="/sweetalert2-11.12.2/sweetalert2@11.js"></script>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-trainMission-add">
			<div class="form-group">
				<label class="col-sm-3 control-label">训练任务名称：</label>
				<div class="col-sm-8">
<!--					默认为当前时间-->
					<input id="trainMissionName" name="trainMissionName"
						   class="form-control" type="text" placeholder="任务名称" >
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">模型：</label>
				<div class="col-sm-8">
					<select id="model" name="model" class="form-control"></select>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">训练数据集：</label>
				<div class="col-sm-8">
					<select id="datasetTrain" name="datasetTrain" class="form-control" type="text"></select>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">验证数据集：</label>
				<div class="col-sm-8">
					<select id="datasetVal" name="datasetVal" class="form-control" type="text"></select>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">batch_size：</label>
				<div class="col-sm-8">
					<input id="batchSize" name="batchSize" class="form-control" type="text" placeholder="4">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">最小训练轮数：</label>
				<div class="col-sm-8">
					<input id="minEpoch" name="minEpoch" class="form-control" type="text" placeholder="100">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">最大训练轮数：</label>
				<div class="col-sm-8">
					<input id="maxEpoch" name="maxEpoch" class="form-control" type="text" placeholder="200">
				</div>
			</div>
<!--			<div class="form-group">	-->
<!--				<label class="col-sm-3 control-label">训练状态：</label>-->
<!--				<div class="col-sm-8">-->
<!--					<input id="status" name="status" class="form-control" type="text">-->
<!--				</div>-->
<!--			</div>-->

			<div class="form-group">
				<label class="col-sm-3 control-label">早停：</label>
				<div class="col-sm-8">
<!--					暗示默认20-->

					<input id="earlyStop" name="earlyStop" class="form-control" type="text" placeholder="20" >

				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">学习率：</label>
				<div class="col-sm-8">
					<input id="opLr" name="opLr" class="form-control" type="text" placeholder="0.0001">
				</div>
			</div>
			<div class="form-group" style="display:none;">
				<label class="col-sm-3 control-label">归属用户：</label>
				<div class="col-sm-8">
					<input id="userId" name="userId" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group" style="display:none;">
				<label class="col-sm-3 control-label">训练数据集id：</label>
				<div class="col-sm-8">
					<input id="datasetTrainId" name="datasetTrainId" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group" style="display:none;">
				<label class="col-sm-3 control-label">验证数据集id：</label>
				<div class="col-sm-8">
					<input id="datasetValId" name="datasetValId" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group" style="display:none;">
				<label class="col-sm-3 control-label">模型id：</label>
				<div class="col-sm-8">
					<input id="modelId" name="modelId" class="form-control" type="text">
				</div>
			</div>

			<!-- 添加是否用预训练权重选项 -->
			<div class="form-group">
				<label class="col-sm-3 control-label">是否使用预训练权重：</label>
				<div class="col-sm-8">
					<!--					是的话值为1，否的话值为0,int型数字,radio-->
					<label class="radio-inline">
						<input type="radio" name="isWeight" value="1" > 是
					</label>
					<label class="radio-inline">
						<input type="radio" name="isWeight" value="0" checked> 否
					</label>
				</div>
			</div>

			<!-- 添加是否公开的选项 -->
			<div class="form-group">
				<label class="col-sm-3 control-label">是否公开：</label>
				<div class="col-sm-8">
<!--					是的话值为1，否的话值为0,int型数字,radio-->
					<label class="radio-inline">
						<input type="radio" name="isPublic" value="1" > 是
					</label>
					<label class="radio-inline">
						<input type="radio" name="isPublic" value="0" checked> 否
					</label>

				</div>
			</div>
		</form>
	</div>
    <div th:include="include::footer"></div>
    <script type="text/javascript">
		var prefix = ctx + "deep_learning/trainMission"
		$("#form-trainMission-add").validate({
			rules:{
				xxxx:{
					required:true,
				},
			},
			focusCleanup: true
		});

		function submitHandler() {
			var trainMissionName = $('#trainMissionName').val();
			if (trainMissionName == null || trainMissionName == "")
			{
				trainMissionName='训练任务'
			}
			$.ajax({
				url: prefix + "/checkTrainMissionName",
				type: "GET",
				data: { name: trainMissionName },
				success: function(response) {
					if (response) {
						Swal.fire({
							icon: 'error',
							title: '错误',
							text: '名称已存在，请使用其他名称',
							showConfirmButton: true,
							allowOutsideClick: false,
							allowEscapeKey: false
						});
					} else {
						if ($.validate.form()) {
							$.operate.save(prefix + "/add", $('#form-trainMission-add').serialize());
						}
					}
				},
				error: function(xhr, status, error) {
					Swal.fire({
						icon: 'error',
						title: '请求失败',
						text: '检查任务名称失败，请稍后重试',
						showConfirmButton: true,
						allowOutsideClick: false,
						allowEscapeKey: false
					});
				}
			});
			window.parent.postMessage('refreshTable', '*');
			// let refreshButton = $("button[name='refresh']");
			// refreshButton.click();
		}
	</script>
	<script >

        $(document).ready(function() {
            let id = null;  // 模型id
            let name = null; // 模型名称
            let user_id = null;  //归属用户id
            let user = null;  //归属用户名
            let isWeight = null;  //是否使用预训练权重

            // ----------模型
            $.ajax({
                url: 'selectModelAndUser',
                type: 'GET',
                processData: false,
                contentType: false,
                success: function (response) {
                    // 假设响应是一个字符串数组
                    let models = response;

                    // 清空现有选项
                    $('#model').empty();

                    // 将每个元素解析为一个选项
                    models.forEach(function(model) {
                        // 假设每个元素的格式为 "id|name|version|user|isWeight"
                        let parts = model.split('|');
                        id = parts[0];  // 模型id
                        name = parts[1]; // 模型名称
                        user_id = parts[2];  //归属用户id
                        user = parts[3];  //归属用户名
                        isWeight = parts[4] === "true";  // 是否使用预训练权重

                        // 显示权重状态
                        let weightStatus = isWeight ? "有权重文件" : "无权重文件";

                        // 创建选项元素，将id存储在value中，将user_id存储在data-user-id属性中
                        let option = new Option(`${name} ------- 归属用户：${user} ------- ${weightStatus}`, name);
                        option.setAttribute('data-user-id', user_id);
                        option.setAttribute('data-model-id', id);
                        option.setAttribute('data-is-weight', isWeight);

                        $('#model').append(option);
                    });

                    // 设置默认选中第一个选项
                    if (models.length > 0) {
                        $('#modelId').val(models[0].split('|')[0]); // 假设第一个元素的id是第一个分割项
                        updateWeightOption(models[0].split('|')[4] === "true"); // 初始化权重选项
                    }

                    // 当选择模型发生变化时，更新相关信息
                    document.getElementById('model').addEventListener('change', function() {
                        let selectedId = this.options[this.selectedIndex].getAttribute('data-model-id'); // 获取id
                        let selectedOption = this.options[this.selectedIndex];
                        let selectedUserId = this.options[this.selectedIndex].getAttribute('data-user-id'); // 获取user_id
                        let selectedName = selectedOption.text.split(' ------- ')[0]; // 提取 name
                        let selectedIsWeight = this.options[this.selectedIndex].getAttribute('data-is-weight') === "true"; // 获取是否有权重文件

                        // 更新模型id
                        $('#modelId').val(selectedId);

                        // 更新使用预训练权重的选项
                        updateWeightOption(selectedIsWeight);
                    });
                },
                error: function (xhr, status, error) {
                    let errorMessage = "请求失败，发生未知错误。";

                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    } else if (xhr.responseText) {
                        try {
                            const jsonResponse = JSON.parse(xhr.responseText);
                            if (jsonResponse.message) {
                                errorMessage = jsonResponse.message;
                            } else {
                                errorMessage = xhr.responseText;
                            }
                        } catch (e) {
                            errorMessage = xhr.responseText;
                        }
                    }
                    Swal.fire({
                        icon: 'error',
                        title: '请求失败',
                        text: '错误信息: ' + errorMessage,
                        showConfirmButton: true,
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    });
                }
            });

            // 更新使用预训练权重的选项
            function updateWeightOption(isWeight) {
                if (isWeight) {
                    // 有权重文件，启用选项
                    $('input[name="isWeight"][value="1"]').prop('disabled', false);
                    $('input[name="isWeight"][value="0"]').prop('checked', false).prop('checked', true);
                } else {
                    // 无权重文件，禁用选项
                    $('input[name="isWeight"][value="1"]').prop('disabled', true);
                    $('input[name="isWeight"][value="0"]').prop('checked', true);
                }
            }
			// ----------------------------------------------训练数据集
			$.ajax({
				url: 'selectDatasetAndUser',
				type: 'GET',
				processData: false,
				contentType: false,
				success: function (response) {
					// 假设响应是一个字符串数组
					let models = response;

					// 将每个元素解析为一个选项
					models.forEach(function(model) {
						// 假设每个元素的格式为 "id|name|version|user"
						let parts = model.split('|');
						id = parts[0];  // 模型id
						name = parts[1]; // 模型名称
						user_id = parts[2];  //归属用户id
						user = parts[3];  //归属用户名

						// 创建选项元素，将id存储在value中，将user_id存储在data-user-id属性中
						let option = new Option(`${name} ------- 归属用户：${user}`, name);
						// console.log('user_id：'+user_id)
						option.setAttribute('data-user-id', user_id);
						option.setAttribute('data-datasetTrain-id', id)
						$('#datasetTrain').append(option);


					});
						// 设置默认选中第一个选项
						if (models.length > 0) {
							// console.log('models[0].split(\'|\')[0]：'+models[0].split('|')[0])
							$('#datasetTrainId').val(models[0].split('|')[0]); // 假设第一个元素的id是第一个分割项
						}
						document.getElementById('datasetTrain').addEventListener('change', function() {
							// console.log('this.value：'+this.value)
							let selectedId = this.options[this.selectedIndex].getAttribute('data-datasetTrain-id');  // 获取id
							let selectedOption = this.options[this.selectedIndex];
							let selectedUserId = this.options[this.selectedIndex].getAttribute('data-user-id'); // 获取user_id
							// console.log(`Selected DatasetTrain ID: ${selectedId}, User ID: ${selectedUserId}`);
							// 	表单赋值
							// console.log('selectedId：'+selectedId)
							$('#datasetTrainId').val(selectedId);
							// console.log(selectedOption.text)
							// $('#datasetTrain').val(selectedOption.text.split(' ------- ')[0])  //
						});
				},
				error: function (xhr, status, error) {
					let errorMessage = "请求失败，发生未知错误。";

					if (xhr.responseJSON && xhr.responseJSON.message) {
						errorMessage = xhr.responseJSON.message;
					} else if (xhr.responseText) {
						try {
							const jsonResponse = JSON.parse(xhr.responseText);
							if (jsonResponse.message) {
								errorMessage = jsonResponse.message;
							} else {
								errorMessage = xhr.responseText;
							}
						} catch (e) {
							errorMessage = xhr.responseText;
						}
					}
					Swal.fire({
						icon: 'error',
						title: '请求失败',
						text: '错误信息: ' + errorMessage,
						showConfirmButton: true,
						allowOutsideClick: false,
						allowEscapeKey: false
					});
				}
			});
			$.ajax({
				url: 'selectDatasetAndUserNoAboutLabel',
				type: 'GET',
				processData: false,
				contentType: false,
				success: function (response) {
					// 假设响应是一个字符串数组
					let models = response;

					// 将每个元素解析为一个选项
					models.forEach(function(model) {
						// 假设每个元素的格式为 "id|name|version|user"
						let parts = model.split('|');
						id = parts[0];  // 模型id
						name = parts[1]; // 模型名称
						user_id = parts[2];  //归属用户id
						user = parts[3];  //归属用户名

						// 创建选项元素，将id存储在value中，将user_id存储在data-user-id属性中
						let option = new Option(`${name} ------- 归属用户：${user}`, name);
						option.setAttribute('data-user-id', user_id);
						option.setAttribute('data-datasetVal-id', id)
						$('#datasetVal').append(option);
						// console.log(option)
					});
						// 设置默认选中第一个选项
						if (models.length > 0) {
							$('#datasetValId').val(models[0].split('|')[0]); // 假设第一个元素的id是第一个分割项
						}
						document.getElementById('datasetVal').addEventListener('change', function() {
							let selectedId = this.options[this.selectedIndex].getAttribute('data-datasetVal-id');  // 获取id
							let selectedUserId = this.options[this.selectedIndex].getAttribute('data-user-id'); // 获取user_id
							// console.log(`Selected DatasetVal ID: ${selectedId}, User ID: ${selectedUserId}`);
							// 	表单赋值
							$('#datasetValId').val(selectedId);
							// console.log(`datasetValId: ${selectedId}`)
							// $('#datasetVal').val(this.options[this.selectedIndex].text.split(' ------- ')[0])  //
						});
				},
				error: function (xhr, status, error) {
					let errorMessage = "请求失败，发生未知错误。";

					if (xhr.responseJSON && xhr.responseJSON.message) {
						errorMessage = xhr.responseJSON.message;
					} else if (xhr.responseText) {
						try {
							const jsonResponse = JSON.parse(xhr.responseText);
							if (jsonResponse.message) {
								errorMessage = jsonResponse.message;
							} else {
								errorMessage = xhr.responseText;
							}
						} catch (e) {
							errorMessage = xhr.responseText;
						}
					}
					Swal.fire({
						icon: 'error',
						title: '请求失败',
						text: '错误信息: ' + errorMessage,
						showConfirmButton: true,
						allowOutsideClick: false,
						allowEscapeKey: false
					});
				}
			});
		// 	---------------------------------------------------------------------添加当前登录用户的id
			$.ajax({
				url: '/deep_learning/app01Dataset/currentUser', // 此地址返回当前用户的 userId
				method: 'GET',
				success: function (response) {
					$('#userId').val(response.userId);
				},
				error: function (xhr, status, error) {
					console.error('请求当前用户信息失败:', error);
				}
			});
		});
	</script>
</body>
</html>
